package com.ruyuan.little.project.rocketmq.api.message.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.little.project.common.dto.CommonResponse;
import com.ruyuan.little.project.common.enums.LittleProjectTypeEnum;
import com.ruyuan.little.project.common.enums.MessageTypeEnum;
import com.ruyuan.little.project.message.api.WxSubscribeMessageApi;
import com.ruyuan.little.project.message.dto.ValueDTO;
import com.ruyuan.little.project.message.dto.WaitPayOrderMessageDTO;
import com.ruyuan.little.project.message.dto.WxSubscribeMessageDTO;
import com.ruyuan.little.project.mysql.api.MysqlApi;
import com.ruyuan.little.project.rocketmq.api.message.dto.OrderInfo;
import com.ruyuan.little.project.rocketmq.api.message.dto.OrderMessage;
import com.ruyuan.little.project.rocketmq.common.utils.DateUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 订单状态顺序消息
 */
@Component
public class OrderMessageListener implements MessageListenerOrderly {


    private static final Logger LOGGER = LoggerFactory.getLogger(OrderMessageListener.class);

    /**
     * mysql dubbo api接口
     */
    @Reference(version = "1.0.0",
            interfaceClass = WxSubscribeMessageApi.class,
            cluster = "failfast",check = false)
    private WxSubscribeMessageApi wxSubscribeMessageApi;


    @Override
    public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {

        for (MessageExt msg : msgs) {
            String content = new String(msg.getBody(), StandardCharsets.UTF_8);
            LOGGER.info("received order  message:{}", content);

            OrderMessage orderMessage = JSON.parseObject(content, OrderMessage.class);
            OrderInfo orderInfo = JSON.parseObject(orderMessage.getContent(), OrderInfo.class);

            try {

                if (Objects.equals(orderMessage.getMessageType(), MessageTypeEnum.WX_CREATE_ORDER)){
                    WaitPayOrderMessageDTO waitPayOrderMessageDTO = this.builderWxOrderMessage(orderInfo);
                    this.send(waitPayOrderMessageDTO,orderInfo.getPhoneNumber());
                }
            } catch (Exception e) {
                LOGGER.error("push wx message fail error message:{}", e.getMessage());
                return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
            }
        }


        return ConsumeOrderlyStatus.SUCCESS;
    }

    /**
     * 实际发送消息
     *
     * @param wxOrderMessage 消息内容
     * @param phoneNumber    手机号
     */
    private void send(WaitPayOrderMessageDTO wxOrderMessage, String phoneNumber) {
        WxSubscribeMessageDTO<WaitPayOrderMessageDTO> subscribeMessageDTO = new WxSubscribeMessageDTO<>();
        subscribeMessageDTO.setContent(wxOrderMessage);
        subscribeMessageDTO.setLittleProjectTypeEnum(LittleProjectTypeEnum.ROCKETMQ);
        subscribeMessageDTO.setMessageTypeEnum(MessageTypeEnum.WX_CREATE_ORDER);
        subscribeMessageDTO.setPhoneNumber(phoneNumber);
        LOGGER.info("start push order message to weixin param:{}", JSON.toJSONString(subscribeMessageDTO));
        CommonResponse response = wxSubscribeMessageApi.send(subscribeMessageDTO);
        LOGGER.info("end push order message to weixin param:{}, response:{}", JSON.toJSONString(subscribeMessageDTO), JSON.toJSONString(response));
    }


    private WaitPayOrderMessageDTO builderWxOrderMessage(OrderInfo orderInfo) {
        WaitPayOrderMessageDTO waitPayOrderMessageDTO = new WaitPayOrderMessageDTO();
        ValueDTO number1 = new ValueDTO();
        // TODO 由于模板字段只能为数字这里用订单id
        number1.setValue(orderInfo.getId());
        waitPayOrderMessageDTO.setNumber1(number1);

        ValueDTO time2 = new ValueDTO();
        long createTime = orderInfo.getCreateTime() * 1000L;
        time2.setValue(DateUtil.format(new Date(createTime), DateUtil.FULL_TIME_SPLIT_PATTERN));
        waitPayOrderMessageDTO.setTime2(time2);

        ValueDTO time10 = new ValueDTO();
        // 创建时间30分钟之后
        long validTime = (orderInfo.getCreateTime() + 30 * 60) * 1000L;
        time10.setValue(DateUtil.format(new Date(validTime), DateUtil.FULL_TIME_SPLIT_PATTERN));
        waitPayOrderMessageDTO.setTime10(time10);

        ValueDTO thing3 = new ValueDTO();
        thing3.setValue(orderInfo.getOrderItem().getTitle());
        waitPayOrderMessageDTO.setThing3(thing3);
        return waitPayOrderMessageDTO;
    }
}
